package com.handmark.pulltorefresh.library.internal;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.AttributeSet;
import android.webkit.WebView;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by JonathanHsia on 2015/12/9.
 * 加载过程不闪烁的webview//增加自定义的滑动监听处理//加入了自定义的请求头了
 */
public class MyWebView extends WebView {
    public MyWebView(Context context) {
        super(context);
    }

    public MyWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public MyWebView(Context context, AttributeSet attrs, int defStyle, boolean privateBrowsing) {
        super(context, attrs, defStyle, privateBrowsing);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        postInvalidate();
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }


    //自定义的滑动监听
    public OnScrollChangeListener mScrollInterface;

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {

        super.onScrollChanged(l, t, oldl, oldt);

        if (mScrollInterface != null) {
            mScrollInterface.onSChanged(l, t, oldl, oldt);
        }
    }

    public void setOnCustomScroolChangeListener(OnScrollChangeListener scrollInterface) {

        this.mScrollInterface = scrollInterface;

    }

    //自定义滑动回调接口
    public interface OnScrollChangeListener {
        void onSChanged(int l, int t, int oldl, int oldt);
    }

    /**
     * 重载父类的方法,统一的加入请求头
     *
     * @param url
     */
    @TargetApi(Build.VERSION_CODES.FROYO)
    @Override
    public void loadUrl(String url) {
        Map<String, String> map = new HashMap<>();
        map.put("User-Agent-App", "Android v" + getVersionCode());
        loadUrl(url, map);
    }

    /**
     * 获取版本号
     * @return 当前应用的版本号
     */
    public int getVersionCode() {
        try {
            PackageManager manager = getContext().getPackageManager();
            PackageInfo info = manager.getPackageInfo(getContext().getPackageName(), 0);
            return info.versionCode;
        } catch (Exception e) {
            return 1;
        }
    }
    
}
